package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/user"})// urlPatterns = {"/hello"}
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users=new ArrayList<>();
        //jdbc 查询
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url ="jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            Connection connection= DriverManager.getConnection(url,"root","111111");
            // if(connection !=null){
            //    System.out.println("连接成功");
            //  }
            String sql ="select * from user";

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            ResultSet resultSet = preparedStatement.executeQuery();


            while ( resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setPass(resultSet.getString(3));
               //把对象添加到集合中
                users.add(user);

                /*int id = resultSet.getInt(1);
                int name = resultSet.getInt(2);
                int pass = resultSet.getInt(3);
                System.out.println(id+"-------"+name+"------"+pass);*/

            }

            resultSet.close();
            preparedStatement.close();
            connection.close();

            //把集合中数据存储到作用域中
            req.setAttribute("users",users);
            req.getRequestDispatcher("/user.jsp").forward(req,resp);//打开页面

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
}